import uuid


def mobile_user_sign_up(db, logger, request):
    try:
        user = db.get_one("Mobile_User", {"username": request.username})
        if user:
            raise ValueError(f"Username {request.username} already exists")
        else:
            unique_id = uuid.uuid5(uuid.NAMESPACE_DNS, request.username).hex
            nickname = getattr(request, "nickname", None) or request.username
            db.insert_one(
                "Mobile_User",
                {
                    "unique_id": unique_id,
                    "username": request.username,
                    "nickname": nickname,
                    "password": request.password,
                },
            )
            # 在User表中插入该用户
            db.upsert_one(
                "User",
                {
                    "name": nickname,
                    "mac_addr": unique_id,
                    "socket_id": "",
                },
                {"mac_addr": unique_id},
            )
            logger.info(f"User {request.username} signed up")
            return {"unique_id": unique_id}
    except Exception as e:
        raise e


def mobile_user_update(db, logger, request):
    try:

        user = db.get_one("Mobile_User", {"unique_id": request.unique_id})
        update_data = {}
        for field in ("nickname", "password"):
            if hasattr(request, field):
                val = getattr(request, field)
                if val:
                    update_data[field] = val

        if user:
            db.update_one("Mobile_User", update_data, {"unique_id": request.unique_id})
            if "nickname" in update_data:
                # 更新用户昵称
                db.upsert_one(
                    "User",
                    {
                        "name": update_data["nickname"],
                    },
                    {"mac_addr": request.unique_id},
                )
            logger.info(f"{user.get('username')} updated")
            return {"unique_id": request.unique_id}
        else:
            raise ValueError(f"Username {request.username} not exists")

    except Exception as e:
        raise e


def mobile_user_sign_in(db, logger, request):
    try:
        user = db.get_one("Mobile_User", {"username": request.username})
        if user:
            if user.get("password") == request.password:
                unique_id = user.get("unique_id")
                logger.info(f"User {request.username} signed in")
                return {"unique_id": unique_id, "nickname": user.get("nickname")}
            else:
                raise ValueError(f"Password for {request.username} is incorrect")
        else:
            raise ValueError(f"Username {request.username} not exists")
    except Exception as e:
        raise e
